package org.giantlizard.cloud.user.token.interceptor;

import org.giantlizard.cloud.user.token.base.CurrentLoginUser;
import org.giantlizard.cloud.user.token.entity.User;
import org.giantlizard.cloud.user.token.service.UserAuthentication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@ConditionalOnClass(name = "org.springframework.web.servlet.HandlerInterceptor")
public class GiantlizardJwtAuthenticationTokenInterceptor implements HandlerInterceptor {

    private final CurrentLoginUser currentUser;

    @Resource(name = "${userAuthentication.name}")
    private UserAuthentication userAuthentication;

    public GiantlizardJwtAuthenticationTokenInterceptor(CurrentLoginUser currentUser) {
        this.currentUser = currentUser;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        User user=userAuthentication.getCurrentUser(request,response);
        if(null==user){
            return false;
        }
        currentUser.setUser(user);
        return true;
    }
}
